Linear regression trendline calculator

Require the gem as per below. We'll require a few more for the notebook


In [1]:
require 'pry'
require 'awesome_print'
require 'nyaplot'

require 'linear_regression_trend'


Out[1]:
true

Usage

Have an array of samples handy, create a trend object like so:

trender = LinearRegressionTrend::Calculator.new(my_array_of_samples)

trended_samples = trender.trend
trend_slope     = trender.slope
trend_intercept = trender.intercept

See the below example for more examples, and a visualisation.


In [2]:
y = [1,2,3,6,10,11,12,12,12,12,15,18,18,16,16,15,14,11,9,9,7,4,2,1,1]
x = (1..y.size).to_a.map { |n| n.to_s }

t = LinearRegressionTrend::Calculator.new(y)

IRuby.display IRuby.table([['Slope', 'Intercept'], [t.slope, t.intercept]])


SlopeIntercept
-0.0638461538461538410.31

Given a known set of samples


In [3]:
chart = Nyaplot::Plot.new 
chart.add(:bar, x, y)
chart.show


The trendline for that sample set should be a descending trend


In [4]:
chart = Nyaplot::Plot.new 
chart.add(:bar, x, t.trend)
chart.show


Non-negative descending trends


In [13]:
y = [1,2,3,0,10,18,18,18,1,1,1,1,0.5,0.5,0.5,0.5,05,0.25,0.25,0.1,0.1,0,0,0,0]
x = (1..y.size).to_a.map { |n| n.to_s }

t = LinearRegressionTrend::Calculator.new(y, non_negative: true)

IRuby.display IRuby.table([['Slope', 'Intercept', 'Conclusion'], [t.slope, t.intercept, t.trend.last]])


SlopeInterceptConclusion
-0.34673076923076917.7754999999999970

In [12]:
chart = Nyaplot::Plot.new 
chart.add(:bar, x, t.trend)
chart.show


It's last few values should be 0, instead of negative


In [10]:
IRuby.display IRuby.table([(1..y.size).to_a.reverse, t.trend.reverse])


252423222120198765432
0000.147423076923076660.49415384615384550.84088461538461521.1876153846153845.0016538461538455.3483846153846145.6951153846153836.0418461538461516.3885769230769216.735307692307697.082038461538459